package com.cupk.controller;

import com.cupk.entity.Admin;
import com.cupk.entity.Movie;
import com.cupk.entity.User;
import com.cupk.service.LoginService;
import com.cupk.service.MovieService;
import com.cupk.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author LY
 * @version 1.0
 */
@WebServlet("/Login")
public class LoginServlet extends HttpServlet {

    private LoginService loginService = new LoginService();
    private MovieService movieService = new MovieService();
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");
        Object object = loginService.login(username,password,type);
        if(object != null) {
            HttpSession session = req.getSession();
            switch (type) {
                case "user":
                    User user = (User) object;
                    session.setAttribute("user",user);
                    //获取喜好并发送到首页
                    List<Movie> tipList =movieService.findByType(user.getHobbies(),true);
                    session.setAttribute("tipList",tipList);
                    req.getRequestDispatcher("index.jsp").forward(req,resp);
                    break;
                case "admin":
                    Admin admin = (Admin) object;
                    session.setAttribute("admin",admin);
                    List<Movie> movieList = movieService.findAll();
                    List<User> userList = userService.findAll();
                    session.setAttribute("movieList",movieList);
                    session.setAttribute("userList",userList);
                    req.getRequestDispatcher("filmAdmin.jsp").forward(req,resp);
                    break;
            }
        }else {
            resp.sendRedirect("login.jsp");
        }
    }
}
